$(document).ready(function(){
	var ajaxQueueArray = [];
	var load = $('span#load_bar').attr('url');

	(function($) {

	// jQuery on an empty object, we are going to use this as our Queue
	var ajaxQueue = $({});

	$.ajaxQueue = function( ajaxOpts ) {
		var jqXHR,
			dfd = $.Deferred(),
			promise = dfd.promise();

		// run the actual query
		function doRequest( next ) {
			jqXHR = $.ajax( ajaxOpts );
			jqXHR.done( dfd.resolve )
				.fail( dfd.reject )
				.then( next, next );
		}

		// queue our ajax request
		ajaxQueue.queue( doRequest );

		// add the abort method
		promise.abort = function( statusText ) {

			// proxy abort to the jqXHR if it is active
			if ( jqXHR ) {
				return jqXHR.abort( statusText );
			}

			// if there wasn't already a jqXHR we need to remove from queue
			var queue = ajaxQueue.queue(),
				index = $.inArray( doRequest, queue );

			if ( index > -1 ) {
				queue.splice( index, 1 );
			}

			// and then reject the deferred
			dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] );
			return promise;
		};

		return promise;
	};

	})(jQuery);
	
	var run = {
		init:function(e,key){
			if(typeof e !== "undefined" || status == 'unprocessed'){
				jQuery.ajaxQueue({
					type: "POST",
					url: e.attr('url'),
					data:{
						option:e.val()
					}
				}).done(function(output){
					if(output == true){
						e.siblings('span.loading').addClass('label label-success').html('<i class="icon-ok"></i>&nbsp;Remarks was saved.');
						ajaxQueueArray[key] = {status : 'processed'};
					}else{
						e.siblings('span.loading').html('<i class="icon-remove"></i>');
					}
				}).fail(function(){
					e.siblings('span.loading').html('<i class="icon-warning-sign"></i>');
				});
			}
		},
		holder: function(e){
			var _holder ={
					status : 'unprocessed',
					ajaxObject : e
			};
			
			ajaxQueueArray.push(_holder);
		}
	};
	
	$('textarea.ajax-change').on('blur',function()
	{
		var val = $(this).val();
		var orgval = $(this).attr('orgval');
		if(val.length >= 0)
		{	
			if(val !== orgval)
			{
				$(this).siblings('span.loading')
					   .removeClass('label label-important label-success')
					   .html('<span style="font:9px bold; display:block;">saving:</span><img src="'+load+'">');
				$(this).attr('orgval',$(this).val());
				//create a holder for objects
				ajaxQueueArray = [];
				run.holder($(this));
				
				// console.log(ajaxQueue);
				//loop
				$.each(ajaxQueueArray,function(i,e)
				{	
					if(e.status == 'unprocessed')
					{
						run.init(e.ajaxObject,i);
					}
				});
			}else{
				
			}
		}else{
			$(this).siblings('span.loading').css('font','12px bold').addClass('label label-important').text('Remarks Cannot be empty or < 10.');
		}
	});
});





